package org.example.watcher;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author shenguangyang
 */
public class CustomChildrenWatcher implements Watcher {
    private static final Logger log = LoggerFactory.getLogger(CustomChildrenWatcher.class);
    private final ZooKeeper zkClient;

    public CustomChildrenWatcher(ZooKeeper zkClient) {
        this.zkClient = zkClient;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        log.info("Watcher监听事件 = {}",watchedEvent.getState());
        log.info("监听路径为 = {}", watchedEvent.getPath());
        log.info("监听的类型为 = {}", watchedEvent.getType()); //  三种监听类型： 创建，删除，更新
        try {
            List<String> children = zkClient.getChildren(watchedEvent.getPath(), this, new Stat());
            log.info("监听的children = {}", children);
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
